<template>
  <div ref="chartContainer" class="chart-container" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import debounce from 'lodash/debounce'; // 如果没有安装 lodash，可以先安装

const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
});

const chartContainer = ref(null);
let chart = null;

const resizeChart = debounce(() => {
  if (chart) {
    chart.resize();
  }
}, 300); // 300ms 去抖动

onMounted(() => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value);
    chart.setOption(props.options);

    // Resize chart on window resize
    window.addEventListener('resize', resizeChart);
  }
});

// Clean up on unmount
onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chart) {
    chart.dispose();
  }
});

// Watch for changes in options and update chart
watch(
  () => props.options,
  (newOptions) => {
    if (chart) {
      chart.setOption(newOptions, true); // Merge options
    }
  },
  { deep: true }
);
</script>

<style>
.chart-container {
  /* Customize the chart container styles if needed */
}
</style>